# usage: add-hockey-teams.py input_names input_stad input_city input_country db_file

import sys, os, re

def ExtractValue(line, field):
    line = line.strip("\n")
    line = line.replace("Флагификация|", "").replace("}}", "").replace("{{", "")
    line = line.replace("флагификация|", "").replace("}}", "").replace("{{", "")
    line = re.sub("\s*{{[^}]+}}\s*", "\t", line)
    line = re.sub("\s*\[\[[^\]]+\]\]\s*", "", line)
    line = re.sub("\s*\[\[Файл:[^\]]+\]\]\s*", "", line)
    
    line = line.replace("|", "")
    
    fields = line.split("\t")
    if (field < len(fields)):
        return fields[field]
    return ""
    

if (len(sys.argv) < 5):
    print ("использование: add-hockey-teams.py input_names input_stad input_city input_country db_file")
    sys.exit(1)

i = 0
with open (sys.argv[1]) as team_name:
    with open (sys.argv[2]) as team_stad:
        with open(sys.argv[3]) as team_city:
            with open(sys.argv[4]) as team_country:
                for line_name in team_name:
                    line_stad = team_stad.readline()
                    line_city = team_city.readline()
                    line_country = team_country.readline()
                    
                    teamName = ExtractValue(line_name, 1)
                    teamStad = ExtractValue(line_stad, 1)
                    teamCity = ExtractValue(line_city, 2)
                    teamCountry = ExtractValue(line_country, -1)
                    
                    teamName = teamName[:teamName.find(" (")]
                    teamStad = teamStad[:teamStad.find(" (")]
                    
                    teamCountry = teamCountry.replace("&quot;", "")
                    teamCountry = teamCountry.replace("СССР", "Россия")
                    teamCountry = teamCountry.replace("Флаг России", "Россия")
                    
                    os.system("add-stadium.py \"%s\" \"%s\" \"%s\"" % (teamStad, teamCity, teamName))
                    os.system("add-team.py \"%s\" 2 \"%s\" \"%s\"" % (teamName, teamCity, teamCountry))
                    
if (len(sys.argv) < 3):
    print ("usage: add-hockey-teams.py input_names input_stad input_city input_country db_file")
    sys.exit(1)
